<template>
  <div>
    <!-- @ready 富文本实例 -->
    <vue-ueditor-wrap
      class="ueditor"
      ref="ueditor"
      :config="myConfig"
      v-model="copyContent"
      :editor-id="editorId"
      forceInit
      @ready="ready"
    ></vue-ueditor-wrap>
    <div class="caretbutton">
      <el-button @click="upimgs">一键上传图片</el-button>
      <el-button
        type="text"
        icon="el-icon-caret-bottom"
        @click="dialogVisible = true"
      ></el-button>
    </div>
    <!-- word转换弹窗 -->
    <el-dialog
      title="word转换器"
      :visible.sync="dialogVisible"
      width="1000px"
      :before-close="queding"
    >
      <ckeditor ref="ckeditor" v-model="showcont"></ckeditor>
      <span slot="footer">
        <el-button @click="quxiao">取 消</el-button>
        <el-button type="primary" @click="queding">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 图片上传弹窗 -->
    <el-dialog
      title="图片上传"
      width="600px"
      :visible.sync="imguploadlog"
      :before-close="imguplog"
    >
      <div v-for="(item, i) in imguplist" :key="i" class="imgupdiv">
        <img
          :src="item.url"
          alt=""
          width="100px"
          height="60px"
          class="imgyulan"
          @click="yulanimg(item.url)"
        />
        <div class="jindut">
          <el-progress
            :stroke-width="20"
            :percentage="item.percentage"
            :status="item.percentage == 100 ? 'success' : 'exception'"
          ></el-progress>
          <div v-if="item.percentage != 100" class="alert">
            <i class="el-icon-error"></i>
            上传失败，请在右侧重新上传，可拖拽！
          </div>
        </div>
        <ImageUpload
          :limit="1"
          :drag="true"
          v-model="item.cuourl"
          v-if="item.percentage != 100"
          :isShowTip="false"
        />
      </div>
      <span slot="footer">
        <el-button type="primary" @click="imguplog">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 图片预览 -->
    <el-dialog
      :visible.sync="dialogimage"
      title="预览"
      width="500px"
      class="imgdialog"
    >
      <img
        :src="dialogImageUrl"
        style="display: block; width: 100%; margin: 0 auto"
      />
    </el-dialog>
  </div>
</template>
<script>
import VueUeditorWrap from 'vue-ueditor-wrap'
import CKEditor from 'ckeditor4-vue'
import $ from 'jquery'
import ImageUpload from '../ImageUpload'
import ImagePreview from '../ImagePreview'
import { getToken } from "@/utils/auth"
import { listTopping } from '@/api/cms/upckeditimg'
export default {
  name: 'baiduEditor',
  components: {
    VueUeditorWrap,
    CKEditor,
    ImageUpload,
    ImagePreview
  },
  data () {
    return {
      dialogimage: false,
      dialogImageUrl: '',
      numimgid: -1,
      imguploadlog: false,
      ueditor: null,
      editorId: `editor-${new Date().getTime()}`, //唯一id,防止editor缓存
      copyContent: '',
      showcont: null,
      dialogVisible: false,
      shuju: '',
      editorInstance: null,
      imguplist: [
      ]
    }
  },
  props: {
    // 富文本高度
    initialFrameHeight: {
      type: Number,
      default () {
        return 300
      }
    },
    // 富文本内容
    content: {
      type: String,
      default: ''
    },
    // 富文本是否只读状态
    readonly: {
      type: Boolean,
      default: false
    }
  },
  methods: {
    yulanimg (url) {
      this.dialogimage = true
      this.dialogImageUrl = url
    },
    imguplog () {
      let imgtwo = []
      this.imguplist.forEach(element => {
        if (element.cuourl != '') {
          imgtwo.push(element)
        }
        element.show = false
      })
      if (imgtwo.length == 0) {
        this.imguploadlog = false
        return
      }
      let richtext = this.copyContent
      let _this = this
      // 替换图片
      richtext.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi, function (match, capture) {
        imgtwo.forEach(item => {
          if (item.url == capture) {
            richtext = richtext.replace(capture, item.cuourl)
            _this.copyContent = richtext
          }
        })
      })
      this.imguplist = []
      this.numimgid = -1
      this.imguploadlog = false
    },
    ready (UE) {
      this.ueditor = UE
    },
    upimgs () {
      this.getImgSrc(this.copyContent)
    },
    quxiao () {
      this.dialogVisible = false
      this.showcont = null
    },
    queding () {
      this.getImgSrc(this.showcont)
      if (this.copyContent == '') {
        this.copyContent = this.showcont
      } else {
        if (this.showcont) {
          this.copyContent += this.showcont
        }
      }
      this.showcont = null
      this.dialogVisible = false
    },
    getImgSrc (richtext) {
      this.imguplist = []
      this.numimgid = -1
      if (!richtext) return
      if (richtext.indexOf('img') == -1) return
      let _this = this
      richtext.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi, function (match, capture) {
        if (capture.indexOf("60.205.158.75:9300") != -1) return
        _this.imguploadlog = true
        _this.numimgid++
        let numid = _this.numimgid
        _this.imguplist.push({
          numimgid: numid,
          url: capture,
          cuourl: '',
          percentage: 0,
          type: null
        })
        // 如果有base64那么就上传，如果没有，先转为base64
        if (capture.indexOf('base64') == -1 && capture.indexOf("60.205.158.75:9300") == -1) {
          _this.getBase64(capture)
            .then(async function (imgsww) {
              _this.imguplist[numid].percentage = 50
              let formData = new FormData()
              let split = imgsww.split(',')
              let bytes = window.atob(split[1])
              let fileType = split[0].match(/:(.*?);/)[1]
              let ab = new ArrayBuffer(bytes.length)
              let ia = new Uint8Array(ab)
              for (let i = 0; i < bytes.length; i++) {
                ia[i] = bytes.charCodeAt(i)
              }
              let file = new Blob([ab], { type: fileType })
              formData.append('file', file)
              listTopping(formData).then(item => {
                _this.imguplist[numid].percentage = 100
                _this.imguplist[numid].url = item.data.url
                richtext = richtext.replace(capture, item.data.url)
                _this.copyContent = richtext
              })
            }, function (err) {
              // alert(err)//打印异常信息
              console.log('转换失败')
            })
          return
        }
        if (capture.indexOf('base64') != -1) {
          let formData = new FormData()
          let split = capture.split(',')
          let bytes = window.atob(split[1])
          let fileType = split[0].match(/:(.*?);/)[1]
          let ab = new ArrayBuffer(bytes.length)
          let ia = new Uint8Array(ab)
          for (let i = 0; i < bytes.length; i++) {
            ia[i] = bytes.charCodeAt(i)
          }
          let file = new Blob([ab], { type: fileType })
          formData.append('file', file)
          listTopping(formData).then(item => {
            _this.imguplist[numid].percentage = 100
            _this.imguplist[numid].url = item.data.url
            richtext = richtext.replace(capture, item.data.url)
            _this.copyContent = richtext
          })
          return
        }
      })
    },
    //上传网络图片
    getBase64 (img) {
      function getBase64Image (img, width, height) {//width、height调用时传入具体像素值，控制大小 ,不传则默认图像大小
        var canvas = document.createElement("canvas")
        canvas.width = width ? width : img.width
        canvas.height = height ? height : img.height
        var ctx = canvas.getContext("2d")
        ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
        var dataURL = canvas.toDataURL()
        return dataURL
      }
      var image = new Image()
      image.crossOrigin = 'anonymous'
      image.src = img
      var deferred = $.Deferred()
      if (img) {
        image.onload = function () {
          deferred.resolve(getBase64Image(image))//将base64传给done上传处理
        }
        return deferred.promise()//问题要让onload完成后再return sessionStorage['imgTest']
      }
    },
  },
  computed: {

    myConfig () {
      // getOpt("serverUrl") **全局搜索**
      let url = process.env.VUE_APP_BASE_API + "/file/upload"
      return {
        // 如果需要上传功能,找后端小伙伴要服务器接口地址,否则无法上传，上传功能需后端配合。
        serverUrl: url,
        headers: {
          Authorization: "Bearer " + getToken()
        },
        // 你的UEditor资源存放的路径,相对于打包后的index.html(路由使用history模式注意使用绝对路径或者填写正确的相对路径)
        UEDITOR_HOME_URL: '/UEditor/',
        // 编辑器不自动被内容撑高
        autoHeightEnabled: false,
        // 初始容器高度
        initialFrameHeight: this.initialFrameHeight,
        // 初始容器宽度
        initialFrameWidth: '100%',
        // 关闭自动保存,默认是true保存
        enableAutoSave: false,
        // 是否启用元素路径，默认是true显示
        elementPathEnabled: false,
        // 是否开启字数统计
        wordCount: false,
        zIndex: 1,
        readonly: this.readonly
      }
    }
  },
  model: {
    prop: 'content',
    event: 'change'
  },
  watch: {
    copyContent (val) {
      let me = this
      me.$emit('change', val)
    },
    content: {
      immediate: true,
      handler (val) {
        let me = this
        me.copyContent = val
      }
    }
  }
};
</script>

<style lang="less" scoped>
.caretbutton {
  position: absolute;
  bottom: 0;
  right: 30px;
  z-index: 1;
}
/deep/ .cke_top {
  display: none;
}
/deep/ .cke_bottom {
  display: none;
}
.imgupdiv {
  display: flex;
  height: 70px;
  .jindut {
    margin-left: 10px;
  }
  .el-progress {
    width: 300px;
    height: 25px;
  }
  .alert {
    // background: #ffeded;
    color: #ff4949;
    font-size: 12px;
    padding-left: 5px;
    line-height: 23px;
    border-radius: 3px;
    width: 260px;
  }
  /deep/ .el-upload--picture-card {
    width: 100px;
    height: 60px;
    line-height: 70px;
  }
  /deep/ .el-upload-list__item {
    width: 100px;
    height: 60px;
  }
  /deep/ .el-upload-dragger {
    width: 100px;
    height: 60px;
  }
}
.imgyulan {
  cursor: pointer;
}
.imgdialog {
  /deep/ .el-dialog__header {
    display: none;
  }
  /deep/ .el-dialog__body {
    padding: 0;
  }
}
</style>


